package com.ikingtech.platform.service.system.dict.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikingtech.framework.sdk.base.model.PageResult;
import com.ikingtech.framework.sdk.dict.model.DictQueryParamDTO;
import com.ikingtech.framework.sdk.utils.Tools;
import com.ikingtech.platform.service.system.dict.entity.DictDO;
import com.ikingtech.platform.service.system.dict.mapper.DictMapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author tie yan
 */
@Slf4j
@Service
@AllArgsConstructor
public class DictService extends ServiceImpl<DictMapper, DictDO> {

    public boolean exist(String id) {
        return this.baseMapper.exists(Wrappers.<DictDO>lambdaQuery()
                .eq(DictDO::getId, id));
    }

    public Boolean nameExist(String name, String tenantCode) {
        return this.baseMapper.exists(Wrappers.<DictDO>lambdaQuery()
                .isNotNull(DictDO::getId)
                .eq(DictDO::getName, name)
                .eq(DictDO::getTenantCode, tenantCode));
    }

    public Boolean nameExist(String id, String name, String tenantCode) {
        return this.baseMapper.exists(Wrappers.<DictDO>lambdaQuery()
                .ne(DictDO::getId, id)
                .eq(DictDO::getName, name)
                .eq(DictDO::getTenantCode, tenantCode));
    }

    public PageResult<DictDO> listPage(DictQueryParamDTO queryParam, String tenantCode) {
        return PageResult.build(this.page(new Page<>(queryParam.getPage(), queryParam.getRows()), Wrappers.<DictDO>lambdaQuery()
                .like(Tools.Str.isNotBlank(queryParam.getName()), DictDO::getName, queryParam.getName())
                .eq(Tools.Str.isNotBlank(queryParam.getType()), DictDO::getType, queryParam.getType())
                .like(Tools.Str.isNotBlank(queryParam.getRemark()), DictDO::getRemark, queryParam.getRemark())
                .eq(DictDO::getTenantCode, tenantCode)
                .orderByDesc(DictDO::getCreateTime)));
    }

    public List<DictDO> listByTenantCode(String tenantCode) {
        return this.list(Wrappers.<DictDO>lambdaQuery()
                .eq(DictDO::getTenantCode, tenantCode)
                .orderByDesc(DictDO::getCreateTime));
    }

    public void removeByTenantCode(String tenantCode) {
        this.remove(Wrappers.<DictDO>query().lambda()
                .eq(DictDO::getTenantCode, tenantCode));
    }

    public String getTypeById(String id) {
        return this.getObj(Wrappers.<DictDO>lambdaQuery()
                .select(DictDO::getType)
                .eq(DictDO::getId, id), String.class::cast);
    }
}
